use json::JsonValue;
use json::object::Object;
use json::number::Number;
use chrono::naive::NaiveDate;

///解析json字符串
#[test]
pub fn json_parse(){
    let parsed: JsonValue = json::parse(r#"
{
    "code": 200,
    "success": true,
    "payload": {
        "features": [
            "awesome",
            "easyAPI",
            "lowLearningCurve"
        ]
    }
}
    "#).unwrap();

    let code: &JsonValue = &parsed["code"];
    let x = code.as_i32().unwrap();
    println!("{}", x);
}

#[test]
pub fn json_object(){
    let mut data = json::object!{
        foo: false,
        bar: null,
        answer: 42,
        list: [null, "world", true]
    };
    println!("{}", data["foo"].as_bool().unwrap());
    let s: String = "Hello".into();
    println!("{}", s);

}

struct User{
    name: String,
    age: u8,
    birthday: chrono::NaiveDate,
}

///实现Into<JsonValue>
impl Into<JsonValue> for User {
    fn into(self) -> JsonValue {
        let mut obj: Object = Object::new();
        obj.insert("name", JsonValue::String(self.name));
        obj.insert("age", JsonValue::Number(Number::from(self.age)));
        obj.insert("birthday", JsonValue::String(self.birthday.format("%Y-%m-%d").to_string()));
        json::JsonValue::Object(obj)
    }
}
#[test]
pub fn obj_to_json(){
    let user = User{
        name: String::from("李四"),
        age: 23,
        birthday: NaiveDate::parse_from_str("2010-03-06", "%Y-%m-%d").unwrap()
    };
    let s = json::stringify(user);
    println!("{}", s);
}